﻿using System;
using System.Runtime.InteropServices;
using MiniBasic_tlb;

namespace MBEditor
{
    class ParserUnavailableException : Exception
    {
        public ParserUnavailableException(string message)
            : base(message)
        {
            ;
        }
    }

    class Parser
    {
        private IMiniBasic parser;
        
        private _ExecutionParameters GetDefaultParams()
        {
            _ExecutionParameters exParams = new _ExecutionParameters();
            exParams.keepConsoleOpen = 0;
            exParams.memoryAreaSize = 0;
            exParams.pathToFile = null;
            return exParams;
        }

        public Parser()
        {
            try
            {
                parser = new MiniBasicImplClass();
            }
            catch (Exception ex)
            {
                throw new ParserUnavailableException("Couldn't create parser object (" + ex.Message + ")\nDid you forget to run register.cmd?");
            }
        }

        public string ExecuteFile(string file)
        {
            string error = null;
            _ExecutionParameters exParams = GetDefaultParams();
            exParams.pathToFile = file;
            try
            {
                parser.ExecuteFile(ref exParams);
            }
            catch (COMException ex)
            {
                error = ex.Message;
            }
            return error;
        }

        public string ExecuteString(byte[] code, bool hasTextLineNumbers)
        {
            string error = null;
            _ExecutionParameters exParams = GetDefaultParams();
            try
            {
                parser.ExecuteString(ref exParams, code, hasTextLineNumbers);
            }
            catch (COMException ex)
            {
                error = ex.Message;
            }
            return error;
        }
    }
}
